package com.hassean.we.admin.controller;

import com.alibaba.fastjson.JSON;
import com.hassean.we.admin.common.constant.CommonConstant;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yajun on 2019/5/19.
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    @RequestMapping("/oauth/token")
    public  String  passAuth(@RequestParam String username,@RequestParam String password,
                            @RequestParam String grant_type, @RequestParam String scope) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(CommonConstant.passAuthUrl+"/auth/oauth/token");
        post.addHeader("Authorization","Basic cGlnOnBpZw==");
        List<NameValuePair> params=new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username",username));
        params.add(new BasicNameValuePair("password",password));
        params.add(new BasicNameValuePair("grant_type","password"));
        params.add(new BasicNameValuePair("scope","server"));
        Map<String ,Object> map =null;
        String result = null;
        //添加参数
        try {
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            HttpResponse response =  client.execute(post);
            HttpEntity entity = response.getEntity();
             result = EntityUtils.toString(entity, "utf-8");
            System.out.println(result);
            map = JSON.parseObject(result, Map.class);
            //System.out.println(" map.get(\"username\"):"+ map.get("user_name"));
            System.out.println("map:"+map );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  result;

}

}




